<!-- src/views/outbound/aaa/OutboundAddDialog.vue -->
<script setup>
import { ref, getCurrentInstance, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { getUserListApi } from '@/api/user';
import { addOutboundOrderApi } from '@/api/outbound/outboundOrder';
import SkuSelector from './SkuSelector.vue';

const instance = getCurrentInstance();

// 弹窗控制
const dialogFormVisible = ref(false);
const title = ref('新增发货单');
const skuSelectorVisible = ref(false);
const selectedSkus = ref([]);

// 表单数据 - 统一字段名与后端一致
const form = ref({
  customerId: '',
  skuVoList: []
});

// 获取货主列表
const userList = ref([]);
const fetchUserList = async () => {
  const res = await getUserListApi();
  userList.value = res.data;
};

// 重置表单
const reset = () => {
  form.value = {
    customerId: '',
    skuVoList: []
  };
  selectedSkus.value = [];
};

// 打开SKU选择器
const openSkuSelector = () => {
  skuSelectorVisible.value = true;
};

// 确认选择SKU - 转换字段格式以匹配后端SkuVo
const handleSkuConfirm = (skus) => {
  selectedSkus.value = skus;
  // 更新表单中的skuVoList字段，字段名与后端SkuVo一致
  form.value.skuVoList = skus.map(sku => ({
    id: sku.id,
    code: sku.code,
    count: sku.count || 1
  }));
};

// 监听selectedSkus变化，同步更新form.value.skuVoList中的count值
watch(selectedSkus, (newSkus) => {
  form.value.skuVoList = newSkus.map(sku => ({
    id: sku.id,
    code: sku.code,
    count: sku.count || 1
  }));
}, { deep: true });

// 提交表单
const save = async () => {
  if (!form.value.customerId) {
    ElMessage.error('请选择客户名称');
    return;
  }
  
  if (form.value.skuVoList.length === 0) {
    ElMessage.error('请至少选择一个商品');
    return;
  }

  // 检查是否有商品数量小于1
  const invalidCount = form.value.skuVoList.some(item => item.count < 1);
  if (invalidCount) {
    ElMessage.error('商品数量至少为1');
    return;
  }

  try {
    // 调用后端API
    await addOutboundOrderApi(form.value);
    ElMessage.success('提交成功');
    dialogFormVisible.value = false;
    instance.emit('refresh');
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message);
  }
};

// 打开弹窗
const open = () => {
  dialogFormVisible.value = true;
  reset();
};

// 关闭弹窗
const close = () => {
  dialogFormVisible.value = false;
};

// 暴露方法给外部调用
defineExpose({
  open,
  close,
  reset
});

onMounted(() => {
  fetchUserList();
});
</script>

<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="600px"
    top="5vh"
  >
    <el-form :model="form" label-width="100px">
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="form.customerId"
          placeholder="请选择客户"
          clearable
          style="width: 100%;"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 商品添加区域 -->
      <el-form-item label="商品信息">
        <el-button type="primary" icon="Plus" @click="openSkuSelector">
          选择商品
        </el-button>
      </el-form-item>

      <!-- 已选商品展示 -->
      <el-form-item v-if="selectedSkus.length > 0" label="">
        <div class="selected-skus-container">
          <div class="table-header">
            <span>已选择 {{ selectedSkus.length }} 项商品</span>
          </div>
          <el-table 
            :data="selectedSkus" 
            size="small" 
            max-height="250"
            stripe
            border
          >
            <el-table-column prop="code" label="商品编码" min-width="100" />
            <el-table-column prop="title" label="商品名称" min-width="120" />
            <el-table-column prop="supplierName" label="供应商" min-width="100" />
            <el-table-column label="数量" min-width="100">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.count" 
                  :min="1" 
                  :max="999999" 
                  size="small"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="save">提交</el-button>
      </div>
    </template>
  </el-dialog>
  
  <!-- SKU选择弹框 -->
  <SkuSelector 
    v-model:visible="skuSelectorVisible" 
    @confirm="handleSkuConfirm" 
  />
</template>

<style scoped>
.selected-skus-container {
  width: 100%;
  margin-top: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 20px;
}
</style>